import React, { useContext, useState } from 'react'
import DecisionNode from '@/Model/Node/DecisionNode'
import { v4 as uuidv4 } from 'uuid'
import {ChapterContext} from '@/hooks/useChapterContext'
import TextField from '@mui/material/TextField'
import NodeCard from './NodeCard'
import CardActions from '@mui/material/CardActions'
import Button from '@mui/material/Button'
import OptionNode from '@/Model/Node/OptionNode'
import OptionCard from './OptionCard'

interface Props{
  data: DecisionNode
}

export default function DecisionCard (props: Props) {
  const cahpterContext = useContext(ChapterContext)
  const [chapter, setChapter] = cahpterContext?.chapter
  const [currentCard, setCurrentCard] = cahpterContext.currentCard
  const [_, setRefresh] = cahpterContext.refresh

  const handleOnChangeQuestion = (event:any) => {
    const newNode = {
      ...props.data,
      question: event.target.value
    }
    chapter.nodes[props.data.uuid] = newNode
    setRefresh(new Date().getTime())
  }

  const addOption = () => {
    const uuid = uuidv4()
    const option:OptionNode = new OptionNode(uuid)
    option.prev = props.data.uuid
    props.data.options.push(uuid)
    chapter.nodes[uuid] = option
    setRefresh(new Date().getTime())
  }

  const handleOnDel = (uuid:string) => {
    const index = props.data.options.findIndex((i) => i === uuid)
    props.data.options.splice(index, 1)
    setRefresh(new Date().getTime())
  }

  const toPrev = (e:any) => {
    e.stopPropagation()
    setCurrentCard(chapter.nodes[props.data.uuid].prev)
  }

  return <NodeCard data={props.data}
    type="选择节点"
    actions={<CardActions>
      <Button onClick={addOption}>增加选项</Button>
      <Button onClick={toPrev}>上一步</Button>
    </CardActions>}
  >
    <TextField variant="standard" onInput={handleOnChangeQuestion} multiline label="问题:" value={props.data.question}
      style={{width: '100%', marginBottom: 10}} />
    {
      props.data.options?.map?.((item:string, index:number):any => (
        <OptionCard
          key={index}
          onDel={handleOnDel}
          data={chapter.nodes[item]} />
      ))
    }


  </NodeCard>
}
